<?php
namespace common\models;

use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use Yii;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $last_login
 * @property string $password write-only password
 */
class User extends ActiveRecord implements IdentityInterface
{
    const ROOT_ID = 1;
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const ROLE_USER = 10;

    private $_password;
    private $_roles;
    private $_roleNames;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'email'], 'required'],
            ['username', 'match', 'pattern' => '/[a-zA-Z0-9]{5,32}/'],
            ['email', 'email'],
            [['username', 'email'], 'unique'],
            ['password', 'required', 'on' => 'create'],
            ['password', 'safe', 'on' => 'create'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
            ['roleNames', 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '用户名',
            'email' => '电子邮箱',
            'password' => '密码',
            'status' => '状态',
            'statusStr' => '状态',
            'roles' => '角色',
            'roleNames' => '角色',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'last_login' => '最后登录',
        ];
    }

    public function scenarios()
    {
        return array_merge(parent::scenarios(), [
            'profile' =>['username', 'email']
        ]);
    }

    public static function getStatusList()
    {
        return [
            self::STATUS_DELETED => '阻止',
            self::STATUS_ACTIVE => '活跃'
        ];
    }

    public function getStatusStr()
    {
        $statusList = self::getStatusList();
        return isset($statusList[$this->status]) ? $statusList[$this->status] : '';
    }

    public static function getRoleList()
    {
        static $list;
        if (!isset($list)) {
            $roles = Yii::$app->getAuthManager()->getRoles();
            $list = [];
            foreach ($roles as $role) {
                $list[$role->name] = $role->description;
            }
        }
        return $list;
    }

    public function getRoles()
    {
        if (!isset($this->_roles)) {
            $this->_roles = Yii::$app->getAuthManager()->getRolesByUser($this->id);
        }
        return $this->_roles;
    }

    public function getRoleNames()
    {
        if (!isset($this->_roleNames)) {
            $this->_roleNames = [];
            foreach ($this->getRoles() as $role) {
                $this->_roleNames[] = $role->name;
            }
        }
        return $this->_roleNames;
    }

    public function setRoleNames($roleNames)
    {
        if (is_array($roleNames)) {
            $roleList = $this->getRoleList();
            foreach ($roleNames as $i => $name) {
                if (!isset($roleList[$name])) {
                    unset($roleNames[$i]);
                }
            }
        } else {
            $roleNames = [];
        }
        $this->_roleNames = $roleNames;
    }

    /**
     * 添加角色
     *
     * @param string $name
     */
    public function addRole($name)
    {
        $roleNames = $this->getRoleNames();
        if (!in_array($name, $roleNames)) {
            $roleNames[] = $name;
            $this->setRoleNames($roleNames);
            $this->saveRoles();
        }
    }

    /**
     * 是否拥有 $name 角色
     *
     * @param string $name
     * @return bool
     */
    public function hasRole($name)
    {
        $roleNames = $this->getRoleNames();
        return in_array($name, $roleNames);
    }

    /**
     * 移除某个角色
     *
     * @param string $name
     */
    public function removeRole($name)
    {
        $roleNames = $this->getRoleNames();
        if (($index = array_search($name, $roleNames)) !== false) {
            unset($roleNames[$index]);
            $this->setRoleNames($roleNames);
            $this->saveRoles();
        }
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    public function getPassword()
    {
        return $this->_password;
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->_password = $password;
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    /**
     * @inheritDoc
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $this->generateAuthKey();
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritDoc
     */
    public function beforeDelete()
    {
        if (parent::beforeDelete()) {
            if ($this->id == self::ROOT_ID) {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritDoc
     */
    public function afterSave($insert, $changeAttributes)
    {
        parent::afterSave($insert, $changeAttributes);
        $this->saveRoles();
    }

    /**
     * @inheritDoc
     */
    public function afterDelete()
    {
        parent::afterDelete();
        $this->removeRoles();
    }

    /**
     * 保存角色
     */
    protected function saveRoles()
    {
        $authManager = Yii::$app->getAuthManager();
        $oldRoles = $this->getRoles();
        $newRoleNames = $this->getRoleNames();
        foreach ($oldRoles as $i => $role) {
            foreach ($newRoleNames as $j => $name) {
                if ($name === $role->name) {
                    unset($newRoleNames[$j]);
                    unset($oldRoles[$i]);
                }
            }
        }

        foreach ($oldRoles as $role) {
            $authManager->revoke($role, $this->id);
        }

        foreach ($newRoleNames as $name) {
            if ($role = $authManager->getRole($name)) {
                $authManager->assign($role, $this->id);
            }
        }
    }

    /**
     * 移除用户所有角色
     */
    protected  function removeRoles()
    {
        $authManager = Yii::$app->getAuthManager();
        $roles = $this->getRoles();
        foreach ($roles as $role) {
            $authManager->revoke($role, $this->id);
        }
    }
}
